from PIL import Image
import os

defaultOutPath = r'C:\Users\da\Desktop\outpath'
outPathBuff = []


def reImgSizeMost(path, outPath=defaultOutPath):
    '''
    实现图片压缩
    1.保持图片大小比例不变
    2.使用Image里面的resize进行
    '''

    if os.path.exists(outPath) is False:
        os.makedirs(outPath)

    count = os.listdir(path)
    for item in range(0, len(count)):
        outPath = os.path.join(outPath, count[item])
        cur_path = os.path.join(path, count[item])
        if os.path.isdir(cur_path):
            outPathBuff.append(outPath)
            reImgSizeMost(cur_path, outPath)
            outPath = outPathBuff[len(outPathBuff) - 1]
            print("")
        else:
            im = Image.open(cur_path)
            (x, y) = im.size  # 读取图片尺寸（像素）
            x_1 = 800  # 定义缩小后的标准宽度
            y_1 = int(y * x_1 / x)  # 计算缩小后的高度
            out = im.resize((x_1, y_1), Image.BOX)  # 改变尺寸，保持图片高品质
            out.save(outPath, quality=30)

            if item == len(count) - 1:
                outPathBuff.remove(outPathBuff[len(outPathBuff) - 1])
            else:
                outPath = outPathBuff[len(outPathBuff) - 1]
            print("保存完成：" + outPath)


def reImgSize(path, newPath, newSize=(500, 500)):
    """
    重新设置image大小
    """
    im = Image.open(path)
    out = im.resize(newSize, Image.ANTIALIAS)  # resize image with high-quality
    out.save(newPath)


def reFormat(path, newFormat):
    """
    重新设置格式
    """
    newPath = ""
    strArr = str(path).split(".")
    if strArr[len(strArr) - 1] != newFormat:
        for item in range(0, len(strArr) - 1):
            newPath = newPath + strArr[item]
        path = newPath + "." + newFormat
    return path


if __name__ == '__main__':
    reImgSizeMost(r'C:\Users\da\Desktop\detail')
